package com.sws.common.utils.access_tokenutil.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

/**
 * HTTP客户端工具类
 */
@Slf4j
public class HttpClientUtil {

    // 增加超时时间以适应内网穿透场景
    private static final int CONNECT_TIMEOUT = 60000; // 连接超时时间，从5秒增加到60秒
    private static final int SOCKET_TIMEOUT = 90000;  // 套接字超时时间，从10秒增加到90秒
    private static final int CONNECTION_REQUEST_TIMEOUT = 60000; // 连接请求超时时间，从5秒增加到60秒

    /**
     * 发送HTTP GET请求
     *
     * @param url     请求URL
     * @param param   请求参数
     * @return 响应内容字符串
     */
    public static String doGet(String url, String param) {
        // 创建HttpClient对象
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建URI
            URI uri = buildUri(url, param);
            
            // 创建HTTP GET请求
            HttpGet httpGet = new HttpGet(uri);
            
            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(CONNECT_TIMEOUT)
                    .setSocketTimeout(SOCKET_TIMEOUT)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                    .build();
            httpGet.setConfig(requestConfig);
            
            log.info("发送HTTP请求，URL: {}, 参数: {}, 超时设置: 连接超时={}ms, 套接字超时={}ms, 连接请求超时={}ms", 
                    url, param, CONNECT_TIMEOUT, SOCKET_TIMEOUT, CONNECTION_REQUEST_TIMEOUT);
            
            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 判断响应状态
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 获取响应内容
                    return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                } else {
                    log.error("HTTP请求失败，状态码：{}", response.getStatusLine().getStatusCode());
                }
            }
        } catch (IOException | URISyntaxException e) {
            log.error("HTTP请求异常", e);
        }
        return null;
    }

    /**
     * 构建URI
     *
     * @param url   基础URL
     * @param param 请求参数
     * @return URI对象
     * @throws URISyntaxException URI语法异常
     */
    private static URI buildUri(String url, String param) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);
        uriBuilder.addParameter("cmd", param);
        return uriBuilder.build();
    }
} 